package com.cctc.juc.demo.Athread.Bcreate.BRunnable;

import java.io.Closeable;
import java.io.IOException;

public class PeriodScheduler implements Runnable, Closeable {
    private final Thread scheduler;
    private long startTime;
    volatile private boolean stop;

    public PeriodScheduler() {
        this.stop = false;
        this.startTime = System.currentTimeMillis() / 1000;
        this.scheduler = new Thread(this, "period-scheduler");
        this.scheduler.setDaemon(true);
        this.scheduler.start();
    }

    @Override
    public void run() {
        while (!stop) {
            long curTime = System.currentTimeMillis() / 1000;
            if (curTime - startTime >= 3) {
                System.out.println("周期调度器：每 3 秒执行一次目标任务... ...");
                startTime = curTime;
            }
        }
    }

    @Override
    public void close() throws IOException {
        startTime = Long.MAX_VALUE;
        stop = true;
    }
}
